<template>
  <div class="student-list">
    <el-card>
      <!-- 搜索和操作栏 -->
      <div class="toolbar">
        <div class="search-area">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索学号、姓名"
            style="width: 200px"
            clearable
            @clear="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
          
          <el-select
            v-model="filters.major"
            placeholder="专业"
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option
              v-for="major in majors"
              :key="major"
              :label="major"
              :value="major"
            />
          </el-select>
          
          <el-select
            v-model="filters.className"
            placeholder="班级"
            clearable
            style="width: 150px"
            @change="handleSearch"
          >
            <el-option
              v-for="cls in classes"
              :key="cls"
              :label="cls"
              :value="cls"
            />
          </el-select>
          
          <el-select
            v-model="filters.status"
            placeholder="状态"
            clearable
            style="width: 120px"
            @change="handleSearch"
          >
            <el-option label="在读" value="enrolled" />
            <el-option label="毕业" value="graduated" />
            <el-option label="休学" value="suspended" />
            <el-option label="退学" value="expelled" />
          </el-select>
          
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
        </div>
        
        <div class="action-area">
          <el-button
            v-if="userStore.checkPermission(Permission.STUDENT_IMPORT)"
            type="success"
            @click="showImportDialog = true"
          >
            <el-icon><Upload /></el-icon>
            导入Excel
          </el-button>
          
          <el-dropdown
            v-if="userStore.checkPermission(Permission.STUDENT_EXPORT)"
            @command="handleExportCommand"
          >
            <el-button type="warning">
              <el-icon><Download /></el-icon>
              导出Excel
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="basic">基础导出</el-dropdown-item>
                <el-dropdown-item command="detailed">详细导出</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
          
          <el-button
            v-if="userStore.checkPermission(Permission.STUDENT_EDIT)"
            type="primary"
            @click="handleAdd"
          >
            <el-icon><Plus /></el-icon>
            添加学生
          </el-button>
        </div>
      </div>
      
      <!-- 学生列表表格 -->
      <el-table
        :data="studentList"
        v-loading="loading"
        stripe
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="student_id" label="学号" width="120" />
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            {{ row.gender === 'male' ? '男' : '女' }}
          </template>
        </el-table-column>
        <el-table-column prop="major" label="专业" width="150" />
        <el-table-column prop="class_name" label="班级" width="120" />
        <el-table-column prop="grade" label="年级" width="100" />
        <el-table-column prop="phone" label="联系电话" width="130" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              link
              @click="handleView(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="userStore.checkPermission(Permission.STUDENT_EDIT)"
              type="warning"
              size="small"
              link
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              v-if="userStore.checkPermission(Permission.STUDENT_DELETE)"
              type="danger"
              size="small"
              link
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :total="total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
        style="margin-top: 20px; justify-content: flex-end"
      />
    </el-card>
    
    <!-- 导入对话框 -->
    <el-dialog
      v-model="showImportDialog"
      title="导入学生信息"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="import-container">
        <!-- 模板下载区域 -->
        <div class="template-section">
          <el-alert
            title="导入说明"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <p>1. 请先下载导入模板，按照模板格式填写数据</p>
              <p>2. 必填字段：学号、姓名、性别、身份证号、专业、班级、年级</p>
              <p>3. 文件格式：Excel (.xlsx 或 .xls)，文件大小不超过 10MB</p>
              <p>4. 数据格式要求：</p>
              <ul style="margin: 5px 0 0 20px; font-size: 12px;">
                <li>学号：6-15位数字</li>
                <li>性别：男/女（支持male/female、M/F）</li>
                <li>身份证号：18位数字（最后一位可为X，建议Excel中设为文本格式）</li>
                <li>年级：1900-2100之间的数字</li>
              </ul>
            </template>
          </el-alert>
          
          <div class="template-download">
            <el-button type="primary" @click="handleDownloadTemplate">
              <el-icon><Download /></el-icon>
              下载导入模板
            </el-button>
          </div>
        </div>
        
        <!-- 文件上传区域 -->
        <div class="upload-section">
          <el-upload
            ref="uploadRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :limit="1"
            accept=".xlsx,.xls"
            drag
            :on-remove="handleFileRemove"
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                只能上传 xlsx/xls 文件，且不超过 10MB
              </div>
            </template>
          </el-upload>
        </div>
        
        <!-- 错误信息显示 -->
        <div v-if="importErrors.length > 0" class="error-section">
          <el-alert
            title="数据验证失败"
            type="error"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="error-content">
                <p><strong>请检查以下错误并修正后重新上传：</strong></p>
                <ul class="error-list">
                  <li v-for="(error, index) in importErrors" :key="index">{{ error }}</li>
                </ul>
                <div class="error-suggestions">
                  <p><strong>常见问题解决方案：</strong></p>
                  <ul>
                    <li>学号：应为6-15位数字，如：2024001、20240001</li>
                    <li>性别：只能是"男"或"女"，也支持"male"/"female"、"M"/"F"</li>
                    <li>身份证号：18位数字，最后一位可为X（注意：Excel可能将长数字转为科学计数法，建议在Excel中将该列格式设为"文本"）</li>
                    <li>联系电话：11位手机号或固定电话格式</li>
                    <li>年级：1900-2100之间的数字</li>
                  </ul>
                </div>
              </div>
            </template>
          </el-alert>
        </div>
        
        <!-- 预览区域 -->
        <div v-if="showPreview" class="preview-section">
          <el-divider content-position="left">数据预览</el-divider>
          <el-table
            :data="importPreviewData"
            max-height="300"
            stripe
            border
          >
            <el-table-column prop="学号" label="学号" width="120" />
            <el-table-column prop="姓名" label="姓名" width="100" />
            <el-table-column prop="性别" label="性别" width="80" />
            <el-table-column prop="专业" label="专业" width="150" />
            <el-table-column prop="班级" label="班级" width="120" />
            <el-table-column prop="年级" label="年级" width="80" />
            <el-table-column prop="联系电话" label="联系电话" width="130" />
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showImportDialog = false">取消</el-button>
          <el-button 
            v-if="importFile && importErrors.length === 0" 
            type="primary" 
            :loading="importing" 
            @click="handleImport"
          >
            确定导入
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 编辑/添加对话框 -->
    <el-dialog
      v-model="showEditDialog"
      :title="editMode === 'add' ? '添加学生' : '编辑学生'"
      width="600px"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="100px"
      >
        <el-form-item label="学号" prop="studentId">
          <el-input v-model="editForm.studentId" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthDate">
          <el-date-picker
            v-model="editForm.birthDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
          <el-input v-model="editForm.idCard" />
        </el-form-item>
        <el-form-item label="专业" prop="major">
          <el-input v-model="editForm.major" />
        </el-form-item>
        <el-form-item label="班级" prop="className">
          <el-input v-model="editForm.className" />
        </el-form-item>
        <el-form-item label="年级" prop="grade">
          <el-input-number v-model="editForm.grade" :min="2000" :max="2100" />
        </el-form-item>
        <el-form-item label="入学日期" prop="enrollmentDate">
          <el-date-picker
            v-model="editForm.enrollmentDate"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" type="textarea" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, FormInstance, FormRules, UploadInstance } from 'element-plus'
import { Search, Upload, Download, Plus, UploadFilled, ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { Student, StudentFilter, Permission, StudentStatus } from '@/types'
import {
  getStudentList,
  createStudent,
  updateStudent,
  deleteStudent,
  importStudents,
  exportStudents,
  exportStudentsToExcel,
  exportStudentsDetailedToExcel,
  getMajors,
  getClasses
} from '@/api/student'
import { exportToExcel, downloadExcelFile, readExcelFile, validateExcelData, downloadImportTemplate, previewExcelData } from '@/utils/excel'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(false)
const studentList = ref<Student[]>([])
const total = ref(0)

const pagination = reactive({
  page: 1,
  pageSize: 20
})

const filters = reactive<StudentFilter>({
  keyword: '',
  major: '',
  className: '',
  status: undefined
})

const majors = ref<string[]>([])
const classes = ref<string[]>([])

const showImportDialog = ref(false)
const showEditDialog = ref(false)
const editMode = ref<'add' | 'edit'>('add')
const uploadRef = ref<UploadInstance>()
const editFormRef = ref<FormInstance>()
const importing = ref(false)
const importFile = ref<File>()
const importPreviewData = ref<any[]>([])
const showPreview = ref(false)
const importErrors = ref<string[]>([])

const editForm = reactive<Partial<Student>>({
  studentId: '',
  name: '',
  gender: '男',
  birthDate: '',
  idCard: '',
  major: '',
  className: '',
  grade: new Date().getFullYear(),
  enrollmentDate: '',
  phone: '',
  email: '',
  address: ''
})

const editRules: FormRules = {
  studentId: [{ required: true, message: '请输入学号', trigger: 'blur' }],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  birthDate: [{ required: true, message: '请选择出生日期', trigger: 'change' }],
  idCard: [
    { required: true, message: '请输入身份证号', trigger: 'blur' },
    { pattern: /^\d{17}[\dXx]$/, message: '身份证号格式不正确', trigger: 'blur' }
  ],
  major: [{ required: true, message: '请输入专业', trigger: 'blur' }],
  className: [{ required: true, message: '请输入班级', trigger: 'blur' }],
  grade: [{ required: true, message: '请输入年级', trigger: 'blur' }],
  enrollmentDate: [{ required: true, message: '请选择入学日期', trigger: 'change' }]
}

const getStatusTagType = (status: StudentStatus) => {
  const typeMap: Record<StudentStatus, any> = {
    [StudentStatus.ENROLLED]: 'success',
    [StudentStatus.GRADUATED]: 'info',
    [StudentStatus.SUSPENDED]: 'warning',
    [StudentStatus.EXPELLED]: 'danger'
  }
  return typeMap[status] || 'info'
}

const getStatusText = (status: StudentStatus) => {
  const textMap: Record<StudentStatus, string> = {
    [StudentStatus.ENROLLED]: '在读',
    [StudentStatus.GRADUATED]: '毕业',
    [StudentStatus.SUSPENDED]: '休学',
    [StudentStatus.EXPELLED]: '退学'
  }
  return textMap[status] || '未知'
}

const fetchStudentList = async () => {
  loading.value = true
  try {
    const res = await getStudentList({
      ...pagination,
      ...filters
    })
    studentList.value = res.list
    total.value = res.total
  } catch (error) {
    console.error('获取学生列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.page = 1
  fetchStudentList()
}

const handleView = (row: Student) => {
  router.push(`/students/${row.id}`)
}

const handleAdd = () => {
  editMode.value = 'add'
  Object.assign(editForm, {
    studentId: '',
    name: '',
    gender: '男',
    birthDate: '',
    idCard: '',
    major: '',
    className: '',
    grade: new Date().getFullYear(),
    enrollmentDate: '',
    phone: '',
    email: '',
    address: ''
  })
  showEditDialog.value = true
}

const handleEdit = (row: Student) => {
  editMode.value = 'edit'
  Object.assign(editForm, row)
  showEditDialog.value = true
}

const handleSave = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      if (editMode.value === 'add') {
        await createStudent(editForm)
        ElMessage.success('添加成功')
      } else {
        await updateStudent(editForm.id!, editForm)
        ElMessage.success('更新成功')
      }
      showEditDialog.value = false
      fetchStudentList()
    } catch (error) {
      console.error('保存失败:', error)
    }
  })
}

const handleDelete = (row: Student) => {
  ElMessageBox.confirm('确定要删除该学生吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteStudent(row.id)
      ElMessage.success('删除成功')
      fetchStudentList()
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

const handleFileChange = async (file: any) => {
  importFile.value = file.raw
  importErrors.value = []
  showPreview.value = false
  
  try {
    // 读取Excel数据
    const data = await readExcelFile(file.raw)
    
    console.log('读取到的Excel数据:', data)
    
    if (!data || data.length === 0) {
      importErrors.value = ['Excel文件为空']
      return
    }
    
    // 打印第一行数据以检查字段名
    if (data.length > 0) {
      console.log('第一行数据的字段:', Object.keys(data[0]))
    }
    
    // 验证数据
    const requiredFields = ['学号', '姓名', '性别', '身份证号', '专业', '班级', '年级']
    const validation = validateExcelData(data, requiredFields)
    
    if (!validation.valid) {
      importErrors.value = validation.errors
      return
    }
    
    // 显示预览
    const { preview } = previewExcelData(data, 5)
    importPreviewData.value = preview
    showPreview.value = true
    
    console.log('预览数据:', preview)
    
    ElMessage.success(`文件解析成功，共 ${data.length} 条数据`)
  } catch (error) {
    console.error('文件解析失败:', error)
    importErrors.value = ['文件解析失败，请检查文件格式是否正确']
  }
}

const handleFileRemove = () => {
  importFile.value = undefined
  importPreviewData.value = []
  showPreview.value = false
  importErrors.value = []
}

const handleImport = async () => {
  if (!importFile.value) {
    ElMessage.warning('请选择要导入的文件')
    return
  }
  
  importing.value = true
  
  try {
    const data = await readExcelFile(importFile.value)
    
    // 再次验证数据
    const requiredFields = ['学号', '姓名', '性别', '身份证号', '专业', '班级', '年级']
    const validation = validateExcelData(data, requiredFields)
    
    if (!validation.valid) {
      importErrors.value = validation.errors
      importing.value = false
      return
    }
    
    // 转换数据格式，支持更多格式
    const students = data.map((row: any, index: number) => {
      // 调试：打印原始数据
      console.log(`处理第 ${index + 2} 行数据:`, row)
      
      // 数据清理和验证 - 使用更安全的方式获取数据
      const studentId = String(row['学号'] || row['studentId'] || '').trim()
      const name = String(row['姓名'] || row['name'] || '').trim()
      const genderRaw = String(row['性别'] || row['gender'] || '').trim()
      const gender = normalizeGender(genderRaw)
      const idCard = String(row['身份证号'] || row['idCard'] || '').trim()
      const major = String(row['专业'] || row['major'] || '').trim()
      const className = String(row['班级'] || row['className'] || '').trim()
      const grade = Number(row['年级'] || row['grade']) || 0
      
      // 调试：打印转换后的数据
      console.log(`转换后数据:`, {
        studentId,
        name,
        gender,
        idCard,
        major,
        className,
        grade
      })
      
      // 验证必填字段
      if (!studentId) {
        throw new Error(`第 ${index + 2} 行学号不能为空`)
      }
      if (!name) {
        throw new Error(`第 ${index + 2} 行姓名不能为空`)
      }
      if (!gender) {
        throw new Error(`第 ${index + 2} 行性别不能为空`)
      }
      if (!idCard) {
        throw new Error(`第 ${index + 2} 行身份证号不能为空`)
      }
      if (!major) {
        throw new Error(`第 ${index + 2} 行专业不能为空`)
      }
      if (!className) {
        throw new Error(`第 ${index + 2} 行班级不能为空`)
      }
      if (grade === 0) {
        throw new Error(`第 ${index + 2} 行年级不能为空`)
      }
      
      const result = {
        studentId,
        name,
        gender,
        birthDate: String(row['出生日期'] || row['birthDate'] || '').trim(),
        idCard,
        major,
        className,
        grade,
        enrollmentDate: String(row['入学日期'] || row['enrollmentDate'] || '').trim(),
        phone: String(row['联系电话'] || row['phone'] || '').trim(),
        email: String(row['邮箱'] || row['email'] || '').trim(),
        address: String(row['地址'] || row['address'] || '').trim()
      }
      
      console.log(`最终结果:`, result)
      return result
    })
    
    // 调用导入API
    console.log('最终发送到服务器的数据:', students)
    await importStudents(students)
    
    ElMessage.success(`成功导入 ${students.length} 条学生信息`)
    showImportDialog.value = false
    fetchStudentList()
    
    // 清理状态
    importFile.value = undefined
    importPreviewData.value = []
    showPreview.value = false
    importErrors.value = []
  } catch (error: any) {
    console.error('导入失败:', error)
    
    // 处理不同类型的错误
    if (error instanceof Error) {
      if (error.message.includes('第') && error.message.includes('行')) {
        // 数据验证错误
        importErrors.value = [error.message]
        ElMessage.error('数据验证失败，请检查错误信息')
      } else if (error.message.includes('500')) {
        // 服务器错误 - 提供更详细的错误信息
        let serverMessage = '服务器错误，请稍后重试'
        
        // 尝试获取服务器返回的详细错误信息
        if (error.response && error.response.data) {
          const serverError = error.response.data
          console.error('服务器错误详情:', serverError)
          
          if (serverError.message && serverError.message !== 'Internal Server Error') {
            serverMessage = `服务器错误: ${serverError.message}`
          } else if (serverError.error && serverError.error !== 'Internal Server Error') {
            serverMessage = `服务器错误: ${serverError.error}`
          }
        }
        
        ElMessage.error(serverMessage)
        
        // 显示详细的调试信息
        ElMessage({
          message: '请检查服务器日志或联系管理员。前端数据格式正确，问题可能出现在服务器端数据处理。',
          type: 'warning',
          duration: 10000,
          showClose: true
        })
      } else if (error.message.includes('网络')) {
        // 网络错误
        ElMessage.error('网络连接失败，请检查网络连接')
      } else {
        // 其他错误
        ElMessage.error('导入失败: ' + error.message)
      }
    } else {
      ElMessage.error('导入失败，请重试')
    }
  } finally {
    importing.value = false
  }
}

const handleDownloadTemplate = () => {
  downloadImportTemplate()
}

// 标准化性别格式
const normalizeGender = (gender: string): string => {
  if (!gender || gender.trim() === '') {
    return '男' // 默认值
  }
  
  const normalizedGender = gender.trim().toLowerCase()
  const genderMap: Record<string, string> = {
    'male': '男',
    'female': '女',
    'm': '男',
    'f': '女',
    'man': '男',
    'woman': '女'
  }
  
  // 如果是中文，直接返回
  if (gender === '男' || gender === '女') {
    return gender
  }
  
  // 如果是英文，转换为中文
  return genderMap[normalizedGender] || gender
}

const handleExportCommand = async (command: 'basic' | 'detailed') => {
  try {
    let blob: Blob
    let filename: string
    
    // 生成安全的文件名，避免特殊字符
    const timestamp = new Date().toISOString().slice(0, 19).replace(/[:.]/g, '-')
    
    if (command === 'basic') {
      blob = await exportStudentsToExcel(filters)
      filename = `学生信息_${timestamp}.xlsx`
    } else {
      blob = await exportStudentsDetailedToExcel(filters)
      filename = `学生详细信息_${timestamp}.xlsx`
    }
    
    // 验证blob是否有效
    if (!blob || blob.size === 0) {
      throw new Error('导出文件为空')
    }
    
    downloadExcelFile(blob, filename)
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败: ' + (error as Error).message)
  }
}

// 保留原有的导出方法作为备用
const handleExport = async () => {
  try {
    const data = await exportStudents(filters)
    
    const columns = [
      { key: 'studentId' as keyof Student, label: '学号' },
      { key: 'name' as keyof Student, label: '姓名' },
      { key: 'gender' as keyof Student, label: '性别' },
      { key: 'birthDate' as keyof Student, label: '出生日期' },
      { key: 'idCard' as keyof Student, label: '身份证号' },
      { key: 'major' as keyof Student, label: '专业' },
      { key: 'className' as keyof Student, label: '班级' },
      { key: 'grade' as keyof Student, label: '年级' },
      { key: 'phone' as keyof Student, label: '联系电话' },
      { key: 'email' as keyof Student, label: '邮箱' }
    ]
    
    exportToExcel(data, columns, '学生信息.xlsx')
  } catch (error) {
    console.error('导出失败:', error)
  }
}

onMounted(async () => {
  fetchStudentList()
  
  // 获取专业和班级列表
  try {
    majors.value = await getMajors()
    classes.value = await getClasses()
  } catch (error) {
    console.error('获取专业班级列表失败:', error)
  }
})
</script>

<style scoped>
.student-list {
  padding: 20px;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.search-area {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.action-area {
  display: flex;
  gap: 10px;
}

/* 导入对话框样式 */
.import-container {
  padding: 10px 0;
}

.template-section {
  margin-bottom: 20px;
}

.template-download {
  margin-top: 15px;
  text-align: center;
}

.upload-section {
  margin-bottom: 20px;
}

.error-section {
  margin-bottom: 20px;
}

.error-content {
  margin: 0;
}

.error-list {
  margin: 10px 0;
  padding-left: 20px;
  max-height: 200px;
  overflow-y: auto;
  color: #f56c6c;
}

.error-suggestions {
  margin-top: 15px;
  padding: 10px;
  background-color: #fff7e6;
  border: 1px solid #ffd591;
  border-radius: 4px;
}

.error-suggestions p {
  margin: 0 0 8px 0;
  color: #d48806;
  font-weight: bold;
}

.error-suggestions ul {
  margin: 0;
  padding-left: 20px;
  color: #d48806;
}

.preview-section {
  margin-bottom: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>

